#include <iostream>
#include <string>
#include <memory>
#include <unistd.h>
#include "Protocol.hpp"
#include "InetAddr.hpp"
#include "Socket.hpp"

using namespace Socket_ns;
using namespace protocol_ns;

void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " serverip serverport\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string serverIP = argv[1];
    uint16_t serverPort = std::atoi(argv[2]);

    // 创建TCP套接字并连接服务器
    std::unique_ptr<Socket> client = std::make_unique<TCPSocket>();
    InetAddr serverAddr(serverIP, serverPort);

    bool ret = client->BuileClientSocket(serverAddr);
    Factory factory;
    std::string out;
    std::string inbuffer;
    while (ret)
    {
        sleep(1);
        // 一次构建多个请求并发送
        // for (int i = 0; i < 5; i++)
        // {
        //     // 构建请求，进行序列化、添加报头
        //     auto request = factory.BuildRequest();
        //     request->Serialize(&out);
        //     out = Encode(out);
        //     LOG(DEBUG, "client send a protocol to server-----------------");
        //     std::cout << out << std::endl;
        //     // 发送请求
        //     client->Send(out);
        // }

        // 构建请求，进行序列化、添加报头
        auto request = factory.BuildRequest();
        request->Serialize(&out);
        out = Encode(out);
        LOG(DEBUG, "client send a protocol to server-----------------");
        std::cout << out << std::endl;
        // 发送请求
        client->Send(out);

        // 接收请求
        client->Recv(&inbuffer);
        LOG(DEBUG, "client recv a protocol-----------------");
        std::cout << inbuffer << std::endl;
        // 去报头，反序列化
        std::string tmp = Decode(inbuffer);
        if (tmp.empty())
            continue;

        auto response = factory.BuildResponse();
        response->DeSerialize(tmp);
        // std::cout << request->_data_x << " " << request->_oper << " " << request->_data_y << " = "
        //           << response->_result << "[" << response->_code << "]" << std::endl;
    }
    return 0;
}
